
/** ************ localStorage ************** */

export function localStorageSave(key, value) {
  localStorage.setItem(key, JSON.stringify(value))
}

export function localStorageGet(key, defaultValue = {}) {
  return JSON.parse(localStorage.getItem(key)) || defaultValue
}

export function localStorageRemove(key) {
  localStorage.removeItem(key)
}
export function localStorageClear() {
  localStorage.clear()
}

/** ************ sessionStorage ************ */

export function sessionStorageSave(key, value) {
  sessionStorage.setItem(key, JSON.stringify(value))
}

export function sessionStorageGet(key, defaultValue = {}) {
  return JSON.parse(sessionStorage.getItem(key)) || defaultValue
}

export function sessionStorageRemove(key) {
  sessionStorage.removeItem(key)
}

export function sessionStorageClear() {
  sessionStorage.clear()
}

/** *************** cookie ***************** */

export function cookieSet(c_name, value, expiredays) {
  if (expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie =
      c_name +
      '=' +
      encodeURIComponent(value) +
      ';expires=' +
      exdate.toGMTString() +
      ';path=/'
  } else {
    document.cookie = c_name + '=' + encodeURIComponent(value)
  }
}

// 读取cookie
export function cookieGet(c_name) {
  let c_start = null
  let c_end = null
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + '=')
    if (c_start !== -1) {
      c_start = c_start + c_name.length + 1
      c_end = document.cookie.indexOf(';', c_start)
      if (c_end === -1) c_end = document.cookie.length
      return decodeURIComponent(document.cookie.substring(c_start, c_end))
    }
  }
  return ''
}

// 检查cookie
export function cookieCheck(c_name) {
  const name = cookieGet(c_name)
  return (name != null && name !== '')
}

// 清除cookie
export function cookieClear(name) {
  cookieGet(name, '', -1)
}
